import React from 'react';
import {
    View,
    StyleSheet,
    FlatList,
    Alert,
    RefreshControl,
    Text,
    InteractionManager,
    TouchableOpacity,
} from 'react-native';

import { connect } from 'react-redux';

import TicketAdd from './ticketAdd';
import { getTickets } from './actions';
import { toast } from '../../utils/NativeUtil';
import moment from 'moment';
import NetUtil from '../../common/NetUtil';
import config from '../../config/config';

import {naviPush} from '../../navigatorApp/actions'

class TicketItem extends React.Component {

  constructor(props) {
    super(props);

    this.page = 0;
  }

  componentDidMount() {
    // console.log("componentDidMount");
    // InteractionManager.runAfterInteractions(() => {
    //   this.page = 1;      
    //   this.loadData()
    // });
  }

  loadData = () => {
    this.props.getTickets(this.props.token, this.page);
  }

  loadMore = () => {
    this.page += 1;
    this.loadData();
  }

  onRefresh = () => {
    this.page = 1;
    this.loadData();
  }

  renderFooter = () => {
    return <View style={{ margin: 10, flex: 1, flexDirection: 'row', justifyContent: 'center' }} >
      <Text style={styles.grayFont}>{this.props.footText}</Text>
    </View>
  }

  stopTicket(ticketid, state, rowData) {
    var self = this;
    let url = '/s/ticket/updateState';
    let updatestate = '';
    if (state == '1') {
      updatestate = '0';
    } else {
      updatestate = '1';
    }

    const params = {
      ticketId: ticketid,
      token: this.props.token,
      state: updatestate,
    }

    NetUtil.postSign(config.apiUrl + url, params, function (res) {
      if (res.success) {
        self.refreshData(rowData, updatestate);
        self.toastmessage('修改成功!');
      }
    });
  }

  editTicket(rowData) {
    // this.props.naviPush('ticketAdd', {token: this.props.token, ticket: rowData})
    // console.log(rowData.state);
    // if (rowData.state == '-2') {
    //   //允许编辑
    //   const nextRouter = {
    //     component: TicketAdd,
    //     title: '卡券编辑',
    //     passProps: {
    //       ticket: rowData,
    //       token: this.props.token
    //     }
    //   };
    //   this.props.navigator.push(nextRouter);
    // }
  }

  refreshData(rowData, ticketstate) {
    rowData.state = ticketstate;
    this.onRefresh();
  }


  chooseDel(ticketid) {
    Alert.alert(
      '是否删除',
      '删除则按确定,否则点取消',
      [
        { text: '取消', onPress: () => console.log('Bar Pressed!')},
        { text: '确定', onPress: () => this.delTicket(ticketid) },
      ]
    );
  }

  //删除卡券
  delTicket(ticketid) {
    var self = this;
    let url = '/s/ticket/deleteShopCoupon';

    const params = {
      id: ticketid,
      token: this.props.token,
    }

    NetUtil.postSign(config.apiUrl + url, params, function (res) {
      if (res.success) {
        self.onRefresh();
        self.toastmessage('删除成功!');
      }
    });
  }

  toastmessage(message) {
    toast(message);
  }

  _renderItem = (item) => { 
    let rowData = item.item;         
    let ticketid = rowData.ticketId;
    let ticketname = rowData.name + ' (¥' + rowData.money/100 + ') ';
    // let ticketinfo = '使用规则:' + rowData.moneyNote;
    let ticketcount = '当前券数量: ' + rowData.num;
    
    let start = "";
    if (rowData.start != undefined) {
      start = dateFormat(new Date(rowData.start), 'yyyy/m/dd');
    }
    let end = "";
    if (rowData.end != undefined) {
      end = moment.unix(rowData.end / 1000).format("YYYY/MM/DD");
    }
    let ticketdate = '使用期:' + start + '--' + end;
    
    let recstart = '';
    if (rowData.receiveStart != undefined) {
      recstart = moment.unix(rowData.receiveStart / 1000).format("YYYY/MM/DD");
    }

    let recend = '';
    if (rowData.receiveEnd != undefined) {
      recend = moment.unix(rowData.receiveEnd / 1000).format("YYYY/MM/DD");
    }
    let recdate = '';
    if (recstart == '' || recend == '') {
      recdate = '投放期:未设置';
    } else {
      recdate = '投放期:' + recstart + '--' + recend;
    }
    
    let ticketevent = '';
    if (rowData.event == 'YYY') {
      ticketevent = '摇一摇';
    } else if (rowData.event == 'AR') {
      ticketevent = 'AR红包';
    } else if (rowData.event == 'USERBUY') {
      ticketevent = '购物返券';
    }
    
    let ticketstate = '';
    let stateColor = '';
    let updatestate = '';
    let btnAction = null;
    if (rowData.state == '1') {
      ticketstate = '已发布';
      stateColor = '#1a9b3b'
      updatestate = '停用';
      btnAction = <TouchableOpacity
        onPress={() => this.stopTicket(ticketid, rowData.state, rowData)}>
        <View style={[custstyles.changebtn, {borderColor: 'red'}]}>
          <Text style={{ color: 'red' }}>{updatestate}</Text>
        </View>
      </TouchableOpacity>;
    } else if (rowData.state == '0') {
      ticketstate = "未发布";
      stateColor = '#fd9155'
      updatestate = '发布';
      btnAction = <TouchableOpacity
        onPress={() => this.stopTicket(ticketid, rowData.state, rowData)}>
        <View style={[custstyles.changebtn, {borderColor: '#1a9b3b'}]}>
          <Text style={{ color: '#1a9b3b' }}>{updatestate}</Text>
        </View>
      </TouchableOpacity>;
    } else if (rowData.state == '-1') {
      ticketstate = '正在审核';
      stateColor = '#fd9155';
      updatestate = '正在审核';
      btnAction = null;
    } else if (rowData.state == '-2') {
      ticketstate = '被拒绝,请重新编辑';
      updatestate = '被拒绝,请重新编辑';
      btnAction = null;
    }
        
    return (
      // <TouchableOpacity onPress={() => this.editTicket(rowData)}>
        <View style={{
          flex: 1,
          backgroundColor: 'white',
          flexDirection: 'column',
          paddingTop: 10
        }}>
        <View style={{
          flex: 1,
          backgroundColor: 'white',
          flexDirection: 'column',
          paddingLeft: 20,
          paddingRight: 20,
          paddingBottom: 10
        }}>
          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
            <Text style={{ fontSize: 18, color: '#fd9155' }}>{ticketname}</Text>
            <Text style={{ fontSize: 14, color: stateColor }}>{ticketstate}</Text>
          </View>
          <Text style={{ marginTop: 8, fontSize: 16 }}>{ticketcount}</Text>
        </View>
        <View style={{ backgroundColor: '#eee', height: 1 }}></View>
        <View style={{
          flex: 1,
          backgroundColor: '#fafafa',
          flexDirection: 'column',
          paddingLeft: 20, 
          paddingRight: 20,
          paddingBottom: 10
        }}>
          <Text style={{ marginTop: 8, fontSize: 14 , color: '#888888'}}>{ticketdate}</Text>
          <Text style={{ marginTop: 8, fontSize: 14 , color: '#888888'}}>{recdate}</Text>
          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
            <Text style={{ fontSize: 16, color: '#fd9155' }}>{ticketevent}</Text>
            <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', }}>
              {btnAction}
              <TouchableOpacity
                onPress={() => this.chooseDel(ticketid)}>
                <View style={custstyles.delbtn}>
                  <Text style={{ color: '#BBBBBB' }}>删除</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        </View>
      // </TouchableOpacity>
    );
  }

  onImageError = (e) => {
  }

  renderSeparator = () => {
    return (<View style={{ backgroundColor: '#eee', height: 10 }} ></View>)
  }

  onEndReached = () => {
    if (this.props.hasMore == true) {
      this.loadMore();
    }
  }

  _keyExtractor = (item, index) => item.ticketId

  render() {
    return (
        <FlatList 
            data={this.props.ticketList}
            extraData={this.props}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderItem}
            onEndReached={this.onEndReached}
            onEndReachedThreshold={0}
            ListFooterComponent={this.renderFooter}
            ItemSeparatorComponent={this.renderSeparator}
            onRefresh={this.onRefresh}
            refreshing={this.props.isRefresh}
        />
    );
  }
}

const mapStateToProps = state => ({
  token: state.mainmodel.token,
  footText: state.ticket.footText,
  hasMore: state.ticket.hasMore,
  ticketList: state.ticket.ticketList,
  isRefresh: state.ticket.isRefresh,
  isLoading: state.ticket.isLoading
});

const mapDispatchToProps = dispatch => ({
  naviPush:(routerName, params) => {
    dispatch(naviPush(routerName, params))
  },
  getTickets: (token, page) => {
    dispatch(getTickets(token, page));
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TicketItem);

const styles = StyleSheet.create({
    grayFont: {
		color: 'gray',
		fontSize: 14,
	},
});

const custstyles = StyleSheet.create({
  delbtn: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 50,
    height: 25,
    backgroundColor: 'white',
    borderRadius: 12.5,
    borderColor: '#BBBBBB',
    borderWidth: 1,
  },
  changebtn: {
    marginRight: 10,
    alignItems: 'center',
    justifyContent: 'center',
    width: 50,
    height: 25,
    backgroundColor: 'white',
    borderRadius: 12.5,
    borderWidth: 1
  }
});